package com.sfd.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.sfd.core.dto.UserDTO;
import com.sfd.core.entity.User;
import com.sfd.core.module.Result;
import com.sfd.core.service.UserService;
import com.sfd.core.vo.LoginUser;
import com.sfd.security.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import utils.*;

import javax.annotation.Resource;

/**
 * @author haden
 * @date 2022/8/13 20:47
 **/
@RequestMapping("/user")
@RestController
@Slf4j
public class UserController {
    @Resource
    private UserService userService;

    @PostMapping("/register")
    public Result<String> register(@RequestBody UserDTO user) {
        try {
            String phone = user.getPhone();
            String username = user.getUsername();
            if (StrUtil.isBlank(username)) {
                username = phone;
            }
            //未设置密码，则随机生成一个密码
            String password = user.getPassword();
            if (StrUtil.isBlank(password)) {
                password = RandomUtil.randomString(8);
            }
            User user1 = userService.getUserByName(username);
            if (user1 != null) {
                return Result.busError("用户名:" + username + "已存在");
            }
            User user2 = userService.getByPhone(phone);
            if (user2 != null) {
                return Result.busError("手机号:" + phone + "已使用");
            }
            User saveUser = new User();
            saveUser.setUsername(username);
            saveUser.setPhone(phone);
            saveUser.setAge(user.getAge());
            saveUser.setBirthday(user.getBirthday());
            //设置盐值
            String salt = ConvertUtils.randomGen(8);
            saveUser.setSalt(salt);
            String passwordEncode = PasswordUtil.encrypt(username, password, salt);
            saveUser.setPassword(passwordEncode);
            userService.save(saveUser);
        } catch (Exception e) {
            return Result.busError("注册失败,原因:" + e.getMessage());
        }
        return Result.success();
    }


    @GetMapping("/createBatch")
    public Result<String> createBatch() {
        for (int i = 0; i < 100; i++) {
            User user = new User(RandInfo.getFamilyName() + RandInfo.getNameAndSex(RandInfo.getSex())[0],
                    "123456", RandomPhoneNumber.createMobile(i % 3),
                    Double.valueOf(100 * Math.random()).intValue(), RandomDate.getRandomDate()
            );
            //设置盐值
            String salt = ConvertUtils.randomGen(8);
            user.setSalt(salt);
            String passwordEncode = PasswordUtil.encrypt(user.getUsername(), user.getPhone(), salt);
            user.setPassword(passwordEncode);
            userService.save(user);
            log.info(i + ":" + JSONObject.toJSONString(user));
        }
        return Result.success();
    }

    @PostMapping("/login")
    public Result<String> login(@RequestBody UserDTO userDTO) {
        try {
            //1.校验登录用户信息
            User user = userService.getUserByName(userDTO.getUsername());
            if (user == null) {
                return Result.busError("用户名不存在");
            }
            //2.校验密码
            String passwordEncode = PasswordUtil.encrypt(userDTO.getUsername(), userDTO.getPassword(), user.getSalt());
            if (!passwordEncode.equals(user.getPassword())) {
                return Result.busError("用户名或密码不正确");

            }
            //3.返回token
            String token = JwtUtil.sign(user.getUsername(), user.getPassword());
            return Result.success(token);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.busError(e.getMessage());
        }
    }

    //退出登录接口

    @GetMapping("/getUser")
    public Result<User> getUser() {
        return Result.success(userService.getUserByName("sona"));
    }

    @GetMapping("/getLoginUser")
    public Result<LoginUser> getLoginUser() {
        LoginUser loginUser = JwtUtil.getLoginUser();
        return Result.success(loginUser);
    }
}
